import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: null,
    isLoggedIn: false,
    userType: 'admin'
  },
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      state.isLoggedIn = !!userInfo
      state.userType = userInfo?.userType || 'admin'
    },
    CLEAR_USER_INFO(state) {
      state.userInfo = null
      state.isLoggedIn = false
      state.userType = 'admin'
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    },
    // 登出
    logout({ commit }) {
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('adminInfo')
      localStorage.removeItem('userType')
      // 清除store状态
      commit('CLEAR_USER_INFO')
    }
  },
  getters: {
    getUserInfo: state => state.userInfo,
    isLoggedIn: state => state.isLoggedIn,
    getUserType: state => state.userType,
    isAdmin: state => state.userType === 'admin',
    isMerchant: state => state.userType === 'merchant'
  }
})
